package com.bw.services.device

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bw.lib_base.base.BaseActivity
import com.bw.services.R
import com.bw.services.databinding.ActivityAddDeviceBinding
import com.bw.services.device.viewmodel.DeviceViewModel
import com.therouter.router.Route
import dagger.hilt.android.AndroidEntryPoint
import android.app.AlertDialog
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import android.content.Context
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import com.bw.common.utils.LogUtil
import com.bw.services.device.model.AddDeviceBody
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = "app/AddDeviceActivity")
class AddDeviceActivity : BaseActivity<ActivityAddDeviceBinding,DeviceViewModel>() {

    override fun generatePremission(pageName: String): Array<String> {
        TODO("Not yet implemented")
    }

    // 只新增：保存输入和选择内容的变量
    private var selectedDeviceType: String? = null
    private var selectedDeviceAddress: String? = null
    private var selectedDeviceStatus: String? = null
    private var inputFaultRate: String? = null
    private var inputDeviceName: String? = null

    override fun setupUI() {
        // 返回按钮
        binding.ivBack.setOnClickListener {
            finish()
        }
        // 设备类型下拉选择
        binding.tvTypeSelect.setOnClickListener {
            val items = arrayOf("门禁设备", "监控设备")
            AlertDialog.Builder(this)
                .setItems(items) { _, which ->
                    binding.tvTypeSelect.text = items[which]
                    selectedDeviceType = items[which]
                }
                .show()
        }
        // 设备地址下拉选择
        binding.tvAddressSelect.setOnClickListener {
            val items = arrayOf("东门", "西门", "南门", "北门")
            AlertDialog.Builder(this)
                .setItems(items) { _, which ->
                    binding.tvAddressSelect.text = items[which]
                    selectedDeviceAddress = items[which]
                }
                .show()
        }
        // 设备状态单选按钮
        binding.rgStatus.setOnCheckedChangeListener { _, checkedId ->
            selectedDeviceStatus = when (checkedId) {
                binding.rbNormal.id -> "正常"
                binding.rbFault.id -> "故障"
                else -> null
            }
        }
        // 故障率输入
        binding.etFaultRate.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                inputFaultRate = binding.etFaultRate.text.toString()
            }
        }
        // 设备名称输入
        binding.etDeviceName.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                inputDeviceName = binding.etDeviceName.text.toString()
            }
        }
        //点击提交
        binding.btnSubmit.setOnClickListener {
            if (selectedDeviceType==null){
                Toast.makeText(this, "请选择设备类型", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (selectedDeviceAddress==null){
                Toast.makeText(this, "请选择设备地址", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (selectedDeviceStatus==null){
                Toast.makeText(this, "请选择设备状态", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (inputFaultRate.isNullOrEmpty()){
                Toast.makeText(this, "请输入设备故障率", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (inputDeviceName.isNullOrEmpty()){
                Toast.makeText(this, "请输入设备名称", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            // 新增：实例化AddDeviceBody对象
            var addDeviceBody = AddDeviceBody(
                id = 0,
                deviceType = selectedDeviceType!!,
                installationLocation = selectedDeviceAddress!!,
                status = selectedDeviceStatus!!,
                failureRate = inputFaultRate!!.toDouble(),
                deviceName = inputDeviceName!!
            )
            // 你可以在此处将addDeviceBody传递给ViewModel等后续逻辑
            Log.d("===",addDeviceBody.toString())
            vm.AddDevice(addDeviceBody)
        }
    }

    override fun fetchData() {
        lifecycleScope.launch {
            vm.addDevicesData.collect{
                LogUtil.d("adddevice",it.toString())
                if (it != null) {
                    ToastFun()
                }
            }
        }
    }
    fun ToastFun(){
        Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show()
    }
    override fun observeData() {

    }

    override fun handleEvent() {
        
    }

    override val mLayoutResId: Int
        get() = TODO("Not yet implemented")

    // 只新增：点击输入框外关闭键盘
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (v != null) {
                val outRect = android.graphics.Rect()
                v.getGlobalVisibleRect(outRect)
                if (!outRect.contains(ev.rawX.toInt(), ev.rawY.toInt())) {
                    v.clearFocus()
                    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v.windowToken, 0)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }
}